package xty.user.dao.impl;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import xty.user.dao.IMongoUserDao;
import xty.user.entity.User;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by XieTianYi on 2019/12/18.
 */
@Repository
public class MongoUserDaoImpl implements IMongoUserDao {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        mongoTemplate.save(user);
    }

    @Override
    public void update(User user) {
        //修改的条件
        Query query = new Query(Criteria.where("id").is(user.getId()));

        //修改的内容
        Update update = new Update();
        update.set("name", user.getName());
        mongoTemplate.updateFirst(query, update, User.class);
    }

    @Override
    public List<User> find(Query query) {
        return mongoTemplate.find(query, User.class);
    }

    @Override
    public List find(Aggregation aggregation) {
        AggregationResults<Map> aggregate = mongoTemplate.aggregate(aggregation, "user", Map.class);
        return aggregate.getMappedResults();
    }

    @Override
    public void delete(String id) {
        User user = mongoTemplate.findById(id, User.class);
        mongoTemplate.remove(user);
    }
}
